package com.hy.demo.controller;


import com.hy.demo.model.InMsgEntity;
import com.hy.demo.model.OutMsgEntity;
import com.hy.demo.util.SignUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;


/**
 * @author cjl
 * @since  2020-7-24
 * @version 1.0
 */
@Controller
@RequestMapping(value = "/weChat")
public class WeChatController {

    @RequestMapping(method = { RequestMethod.GET })
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                out.print(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null)
                out.close();
        }
    }

    /**
     * 微信消息处理
     *
     * 手机公众号总显示“改公众号提供的服务出现故障，请稍后再试”，
     * 在RequestMapping 加了produces= {MediaType.TEXT_XML_VALUE} 类型才可以
     */
    @RequestMapping(method = RequestMethod.POST,produces= {MediaType.TEXT_XML_VALUE})
    @ResponseBody
    public Object handleMessage(@RequestBody InMsgEntity msg) {
        //创建消息响应对象
        OutMsgEntity out = new OutMsgEntity();
        //把原来的发送方设置为接收方
        out.setToUserName(msg.getFromUserName());
        //把原来的接收方设置为发送方
        out.setFromUserName(msg.getToUserName());
        //获取接收的消息类型
        String msgType = msg.getMsgType();
        //设置消息的响应类型
        out.setMsgType(msgType);
        //设置消息创建时间
        out.setCreateTime(new Date().getTime());
        //根据类型设置不同的消息数据
        if("text".equals(msgType)){
            if(StringUtils.equals("马老二",msg.getContent())){
                out.setContent("瓜皮");
            }else if(StringUtils.equals("阿彬",msg.getContent())){
                out.setContent("憨批");
            }else{
                out.setContent(msg.getContent());
            }
        }else if("image".equals(msgType)){
            out.setMediaId(new String[]{msg.getMediaId()});
        }
        return out;
    }
}
